<?php

/**
 * User:ayou chow
 * Date: 2019-11-05
 * Time: 15:55
 */

namespace app\guild\controller;


use app\common\model\GuildManagerModel;
use app\common\model\GuildModel;
use app\common\model\GuildProfitModel;
use app\common\model\LiveHistoryModel;
use app\common\model\LiveModel;
use app\common\model\UserModel;
use app\common\model\RegSourceModel;
use think\facade\Request;
use think\Validate;

class IndexController extends BaseController
{

    public function index()
    {
        $this->assign('config_pub', getConfigPub());
        $this->assign("guild_info", $this->guild_info);
        $this->assign("guild_manager", $this->guild_manager);
        $this->assign('hight_auth', $this->hight_auth);
        $this->assign('role_id', $this->role_id);
        $this->assign('view_livemenu', implode(',', config('other.guild_view_live')));
        return $this->fetch();
    }

    public function home()
    {
        // 直播人数
        $where = [
            ['status', '=', 1],
            ['anchorid', 'in', parent::getGuildUserId()],
        ];

        $live_count = LiveModel::where($where)->count();
        $on_live    = LiveModel::with(['user' => function ($query) {
            $query->field('id,nick_name,avatar');
        }])->where($where)->order('hot', 'desc')->limit(10)->select();

        $this->assign('live_count', $live_count);
        $this->assign('on_live', $on_live);
        $this->assign('hight_auth', $this->hight_auth);
        return $this->fetch();
    }

    public function data_statis()
    {
        $type        = Request::get('type', 1, 'intval');
        $manager_uid = parent::getGuildUserId();

        $start_time = date('Y-m-d 00:00:00');
        $end_time   = date('Y-m-d 23:59:59');

        switch ($type) {
            case 1:
                $start_time = date('Y-m-d 00:00:00');
                $end_time   = date('Y-m-d 23:59:59');
                break;
            case 2:
                $start_time = date('Y-m-d 00:00:00', strtotime("-1 day"));
                $end_time   = date('Y-m-d 23:59:59', strtotime("-1 day"));
                break;
            case 3:
                $start_time = date('Y-m-01 00:00:00');
                $end_time   = date('Y-m-d 23:59:59');
                break;
        }

        // 总克拉
        $t_where = [
            ['guild_id', '=', $this->guild_id],
            ['create_time', 'between', [$start_time, $end_time]]
        ];
        if ($this->hight_auth != 1) {
            // 查询自己及下级经纪人
            $next_manager = self::getNextManager();
            $t_where[]    = ['guild_manager_id', 'in', $next_manager];
        }
        $total_diamond = GuildProfitModel::where($t_where)->sum('diamond');

        // 入驻人数
        $join_where = [
            ['id', 'in', $manager_uid],
            ['guild_join_time', 'between', [$start_time, $end_time]]
        ];
        $join_count = UserModel::where($join_where)->group('id')->count();

        // 直播人数
        $onlive_where = [
            ['anchorid', 'in', $manager_uid],
            ['end_time', 'between', [$start_time, $end_time]],
        ];

        $on_live_count   = LiveModel::whereIn('anchorid', $manager_uid)->where('status', 1)->group('anchorid')->column('anchorid');
        $on_live_history = LiveHistoryModel::where($onlive_where)->group('anchorid')->column('anchorid');

        $onlive_anchor = count(array_unique(array_merge($on_live_count, $on_live_history)));
        if ($type == 2) {
            $onlive_anchor = count($on_live_history);
        }

        // 注册用户数
        $reg_sources = RegSourceModel::where([['guild_id', '=', $this->guild_id]])->select();

        $source_keys = [];
        foreach ($reg_sources as $key => $value) {
            array_push($source_keys, $value['source_key']);
        }

        $regist_count = UserModel::where([['reg_source_id', 'in', $source_keys], ['regist_time', '>=', $start_time], ['regist_time', '<=', $end_time]])->count();

        $data = [
            'hour_str'      => date('H:i'),
            'total_diamond' => $total_diamond,
            'manage_anchor' => count($manager_uid),
            'join_anchor'   => $join_count,
            'onlive_anchor' => $onlive_anchor,
            'regist_count'  => $regist_count,
        ];

        return json($data);
    }

    public function channel()
    {
    }

    public function daily_list()
    {
    }

    /**
     * 代理基本信息
     * @return mixed
     */
    public function guild_info()
    {
        $member_count = UserModel::where("guild_id", $this->guild_id)->count();

        $this->guild_info->member_count = $member_count;

        $manager_info = GuildManagerModel::where(['guild_id' => $this->guild_id, 'role_id' => 1])->find();

        // 注册用户数
        $reg_sources = RegSourceModel::where([['guild_id', '=', $this->guild_id]])->select();

        $source_keys = [];
        foreach ($reg_sources as $key => $value) {
            array_push($source_keys, $value['source_key']);
        }

        $regist_count = UserModel::where([['reg_source_id', 'in', $source_keys]])->count();

        $this->assign("regist_count", $regist_count);
        $this->assign("manager_info", $manager_info);
        $this->assign("guild_info", $this->guild_info);
        $this->assign('hight_auth', $this->hight_auth);
        return $this->fetch();
    }

    public function edit()
    {
        parent::checkHightAuth(0);

        $this->assign('guild_info', $this->guild_info);
        return $this->fetch();
    }

    public function edit_post()
    {
        parent::checkHightAuth();

        $all_param = Request::only('name,icon,content');

        $validate = new Validate([
            'name' => 'require|length:2,16|chsDash',
        ], [
            "name.require" => "代理名称不能为空",
            "name.length"  => "代理名称在2-16个字符",
            "name.chsDash" => "代理名称中文、英文、_和-组成",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        // 代理名称不能重复
        $cg_where = [
            ['name', '=', $all_param['name']],
            ['id', '<>', $this->guild_id]
        ];

        $check_guild_name = GuildModel::where($cg_where)->find();
        if (!empty($check_guild_name)) {
            return self::bulidFail('代理名称已经存在');
        }

        if ($this->guild_info->save($all_param)) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function editpwd()
    {
        return $this->fetch();
    }

    public function editpwd_post()
    {
        $new_pwd    = Request::param("newpwd");
        $manager_id = $this->manager_id;
        if (!$manager_id) {
            $this->redirect(url('Login/redirectpage'));
            exit;
        }

        if (!preg_match('/^[\S]{6,12}$/', $new_pwd)) {
            return self::bulidFail("密码在6-12位且不能有空格");
        }

        $guild_manager = GuildManagerModel::get($manager_id);
        $oldpwd        = openssl_encrypt(substr($guild_manager->mobile, strlen($guild_manager->mobile) - 4, 4) . Request::param("oldpwd"), "DES-ECB", $this->OPENSSL_KEY);
        if ($oldpwd != $guild_manager->password) {
            return self::bulidFail('旧密码验证失败');
        }
        $guild_manager->password = openssl_encrypt(substr($guild_manager->mobile, strlen($guild_manager->mobile) - 4, 4) . $new_pwd, "DES-ECB", $this->OPENSSL_KEY);
        if ($guild_manager->save()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function noOperation()
    {
        return json(["code" => 0, "msg" => ""]);
    }

    public function signForCos()
    {
        return parent::signForCos();
    }
}
